<?php
class WCDBLayer{
	private $url;
	private $user;
	private $password;
	private $conn;
	
	public function __construct($url,$user,$password){
		$this->url = $url;
		$this->user = $user;
		$this->password = $password;
	}
	
	function sanitize($input){
	    if(is_array($input)){
	        foreach($input as $k=>$i){
	            $output[$k]=sanitize($i);
	        }
	    }
	    else{
	        if(get_magic_quotes_gpc()){
	            $input=stripslashes($input);
	        }       
	        $output=mysql_real_escape_string($input);
	    }   
	   
	    return $output;
	}
	
	public function tableExists($table) {
		// open db connection
		$result = mysql_query("show tables like '$table'",$this->conn);
		if($result == false || mysql_num_rows($result)>0){
			return true;
		}else{
			return false;
		}
	}
	
	public function getPassword(){
		return $this->password;
	}
	
	public function setPassword($password){
		$this->password = $password;
	}
	
	public function getConnection(){
		return $this->conn;
	}
	
	public function getUser(){
		return $this->user;
	}
	
	/**
	 * Sets the user to the specified value
	 * 
	 * @param $user
	 * @return none
	 */
	public function setUser($user){
		$this->user = $user;
	}
	
	/**
	 * Creates a connection with the database.
	 * 
	 * @param $db - name of the database to connect to
	 * @return none
	 */
	public function connect($db){
		
		//only one connection per instance of the class
		if(isset($this->conn)){
			mysql_close($this->conn);
		}
		
		// Connect to the database server
	    $this->conn = @mysql_connect($this->url,$this->user,$this->password);
	    if(!$this->conn){
	    	throw new WCException(WCException::$DB_CONN_ERROR,'Unable to connect with credentials: url-'.$this->url.' user-'.$this->user.' ');
	    }
	
	    // Select the database
	    if (!@mysql_select_db($db)){
	    	throw new WCException(WCException::$DB_CONN_ERROR,'Unable to select database, '+$db);
	    }
	}
	
	/**
	 * Executes the query that's passed in
	 * 
	 * @param $query
	 * @return result of the execution of the query
	 */
	public function executeQuery($query){
		echo $query;
		if($this->conn == null){
			throw new WCException(WCExcepion::$DB_CONN_ERROR,'Unable to execute insert query, not connected to the database.');
		}
		$result = mysql_query($query,$this->conn);
		if(!$result){
			throw new WCException(WCException::$DB_QUERY_ERROR,'Error \''.mysql_error().'\' encountered executing query: '.$query);
		}
		return $result;
	}
	
	/**
	 * Builds a select query from data passed into it.
	 * 
	 * @param $table - name of the table for the query to select against
	 * @param $attributes - a list of attributes for the select statement to retrieve
	 * @param $condition - the where clause of the query, will replace ? characters with the sequential values in the condition_data array
	 * @param $condition_data - a list of condition_data to replace the ? characters 
	 * @return result of the execution of the query
	 */
	public function retrieve($table,$attributes,$condition,$condition_data = array()){
		$query = 'SELECT';
		foreach($attributes as $attribute){
			$query.= " $attribute,";
		}
		$query = substr($query,0,-1);
		$query.=" FROM $table WHERE $condition";
		if(sizeof($condition_data) > 0){
			$query = $this->prepare($query,$condition_data);
		}
		return $this->executeQuery($query);
	}
	
	/**
	 * Replaces all ? values with the values in the data array, in order.
	 * 
	 * @param $query
	 * @param $data
	 * @return a cleaned query with all of the ? characters replaced with values
	 */
	public function prepare($query,$data){
		for($i=0;strpos($query,'?') !== false;$i++){
			if($i == sizeof($data)){
				throw new WCException(WCException::$DB_QUERY_ERROR,"Index out of bounds while attempting to replace values.  Current index: $i");
			}
			$query = $this->str_replace_count('?',$this->sanitize($data[$i]),$query,1);
		}
		return $query;
	}
	
	/**
	 * Had to put this bad boy in because PHP doesn't support replacing items in a string
	 * a user specified number of times. (which is what this does)
	 * 
	 * @param $search string to search for
	 * @param $replace string to replace
	 * @param $subject subject of search
	 * @param $times number of times to replace
	 * @return return the string with replacements made
	 */
	private function str_replace_count($search,$replace,$subject,$times) {
	    $subject_original=$subject;
	    $len=strlen($search);    
	    $pos=0;
	    for ($i=1;$i<=$times;$i++) {
	        $pos=strpos($subject,$search,$pos);
	        if($pos!==false) {                
	            $subject=substr($subject_original,0,$pos);
	            $subject.=$replace;
	            $subject.=substr($subject_original,$pos+$len);
	            $subject_original=$subject;
	        } else {
	            break;
	        }
	    }
	    return($subject);
	}
}
?>